package com.rykj.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Description: author: zhangsan on 16/11/21 下午5:38.
 */

public class FileUtil {
    private static final String TAG = "FileUtil";

    private static final String SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath();

    private static final String QINIU_BASEURL = "http://owbrsfqoz.bkt.clouddn.com/";

    public static String PATH = SDPATH + "/" + "stock/";
    public static String IMAGEPATH = PATH + "image/";
    public static String CROP_PATH = PATH + "crop/";


    public static String getImageUrl(String API_URL, String name) {
        if (TextUtils.isEmpty(name) || name.startsWith("http://")) {
            return name;
        }
        return String.format("%s%s", API_URL, name);
    }

    public static String getCropPath() {
        createFilePath(CROP_PATH);
        return CROP_PATH;
    }

    public static String getImagePath(String fileName) {
        StringBuilder sb = new StringBuilder(IMAGEPATH);
        sb.append(fileName);
        createFilePath(IMAGEPATH);
        return sb.toString();
    }


    public static String getQiniuUrl(String fileName) {
        return new StringBuilder(QINIU_BASEURL).append(fileName).toString();
    }

//    /**
//     * 七牛用户头像地址
//     * @param fileName
//     * @return
//     */
//    public static String imageHeaderUrl="";
//
//    public static String getQiniuHeaderUrl(String fileName) {
//        if (TextUtils.isEmpty(imageHeaderUrl)) {
//            imageHeaderUrl = DbHelper.getInstance().getItemCode(C.ParentName.QINIU_USER_IMGURL);
//        }
//        return new StringBuilder(imageHeaderUrl).append(fileName).toString();
//    }


    // 创建文件夹
    public static void createFilePath(String path) {
        String filepath = path.substring(0, path.lastIndexOf("/"));
        File file = new File(path);
        File filesPath = new File(filepath);
        if (!filesPath.exists()) {
            createFilePath(filepath);
            file.mkdir();
        } else {
            file.mkdir();
        }
    }


    public static File saveBitmapFile(Bitmap bitmap) {
        return saveBitmapFile(bitmap, null, true);
    }

    public static File saveBitmapFile(Bitmap bitmap, FileCallBack callBack, boolean recycle) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_sss", Locale.getDefault());
        String fileName = sf.format(new Date());
        fileName = fileName + ".jpg";
        return saveBitmapFile(bitmap, fileName, recycle, callBack);
    }

    public static File saveBitmapFile(Bitmap bitmap, String fileName, FileCallBack callBack) {
        return saveBitmapFile(bitmap, fileName, true, callBack);
    }

    /**
     * @param recycle
     *         是否 回收 bitmap
     */
    public static File saveBitmapFile(Bitmap bitmap, String fileName, boolean recycle, FileCallBack callBack) {
        String imagePath = getImagePath(fileName);
        LogX.d(TAG, "saveBitmapFile: imagePath ：" + imagePath);
        File file = new File(imagePath);//将要保存图片的路径
        if (!file.exists()) {
            try {
                boolean isOk = file.createNewFile();
                LogX.d(TAG, "saveBitmapFile: createNewFile ：" + isOk);
            } catch (IOException e) {
                e.printStackTrace();
                if (callBack != null) {
                    callBack.FileResult(FileCallBack.RESULT_FAIL);
                }
                LogX.e(TAG, "saveBitmapFile: ", e);
            }
        } else {
            if (callBack != null) {
                callBack.FileResult(FileCallBack.RESULT_FAIL);
            }
            LogX.d(TAG, "saveBitmapFile: file ：已存在");
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            if (callBack != null) {
                callBack.FileResult(FileCallBack.RESULT_SUCCEED);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.FileResult(FileCallBack.RESULT_FAIL);
            }
        } finally {
            if (bitmap != null && recycle) {
                bitmap.recycle();
            }
        }
        return file;
    }


    /**
     * 保存 ic_logo.png 到手机的存储卡里
     */
    public static void saveSDFile(Context context) {
        String apkFile = FileUtil.getImagePath("ic_logo.png");
        File file = new File(apkFile);

        if (!file.exists() || file.length() == 0) {
            InputStream in = null;
            FileOutputStream out = null;
            try {
                in = context.getApplicationContext().getAssets().open("ic_logo.png");

                out = new FileOutputStream(file);
                byte[] buffer = new byte[10 * 1024];
                int bytesum = 0;
                int byteread = 0;
                while ((byteread = in.read(buffer)) != -1) {
                    bytesum += byteread;
                    out.write(buffer, 0, byteread);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 根据byte数组生成文件
     * @param bytes
     *         生成文件用到的byte数组
     */
    public static void createFileWithByte(byte[] bytes, String fileName, FileCallBack callBack) {
        /*
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */

        String apkFile = FileUtil.getImagePath(fileName);
        File file = new File(apkFile);

        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try { // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(bytes);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();

            if (callBack != null) {
                callBack.FileResult(FileCallBack.RESULT_SUCCEED);
            }

        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();

            if (callBack != null) {
                callBack.FileResult(FileCallBack.RESULT_FAIL);
            }

        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }


    public interface FileCallBack {
        /**
         * 操作文件成功  返回
         */
        int RESULT_SUCCEED = 0;
        /**
         * 操作文件失败  返回
         */
        int RESULT_FAIL = -1;

        /**
         *
         */
        void FileResult(int result);

    }

}
